<template>
  <div class="page-box ">
    <el-card class="from_box" shadow="hover">
      <el-form v-loading="loading" ref="from" :model="from">
        <el-form-item class="cenCen">
          <el-radio v-model="from.area" label="0" border>无区域领导评分的流程</el-radio>
          <el-radio v-model="from.area" label="1" border>有区域领导评分的流程</el-radio>
          <el-radio v-model="from.area" label="2" border>员工考核计划审核流程</el-radio>
        </el-form-item>
        <el-form-item label-width='100' label="流程名称">
          <el-input v-model.trim="from.name" maxLength="100" placeholder='请输入' clearable></el-input>
        </el-form-item>
        <!--  评分部分 -->
        <el-form-item v-if="!isAssessment" label-width='100' :class="{'el-form-item-operation':from.code.split(',').length>8}" label="提交员工">
          <el-button @click="complexPicker('user_ids')" style="width: 100%;text-align:left;overflow:hidden;" plain>{{from.code?from.code:"请选择"}}</el-button>
          <el-tooltip effect="dark" content="详情" placement="top-start">
            <el-button v-show="from.code.split(',').length>8" @click="showDrawer=true" class="el-form-item-operation_btn" icon="el-icon-more" circle></el-button>
          </el-tooltip>
        </el-form-item>
        <el-form-item v-if="!isAssessment" label-width='100' label="上级评分领导">
          <el-button @click="complexPicker('levelOne')" style="width: 100%;text-align:left;" plain>{{from.levelOne.code?from.levelOne.code:"请选择"}}</el-button>
        </el-form-item>
        <el-form-item v-if="from.area=='1'&&!isAssessment" label-width='100' label="区域评分领导">
          <el-button @click="complexPicker('levelTwo')" style="width: 100%;text-align:left;" plain>{{from.levelTwo.code?from.levelTwo.code:"请选择"}}</el-button>
        </el-form-item>
        <el-form-item v-if="!isAssessment" label-width='100' label="HR评分人员">
          <el-button @click="complexPicker('levelThree')" style="width: 100%;text-align:left;" plain>{{from.levelThree.code?from.levelThree.code:"请选择"}}</el-button>
        </el-form-item>
        <el-form-item v-if="!isAssessment" v-for="(item, index) in nextLeader" :key="index" label-width='100' class="el-form-item-operation" label="下一级审核领导">
          <el-button @click="complexPicker('nextLeader',index)" style="width: 100%;text-align:left;" plain>{{item.code?item.code:"请选择"}}</el-button>
          <el-tooltip effect="dark" content="继续添加审核领导" placement="top-start">
            <el-button @click="addNextLeader()" v-if="index==nextLeader.length-1" class="el-form-item-operation_btn" icon="el-icon-plus" circle></el-button>
          </el-tooltip>
          <el-button @click="deltedNextLeader(index)" v-if="index!=nextLeader.length-1" class="el-form-item-operation_btn" icon="el-icon-delete" circle></el-button>
        </el-form-item>
        <el-form-item v-if="!isAssessment" class="cenCen" label-width='100' label="">
          <el-button @click="subFrom()" icon="el-icon-circle-check" style="width:400px" type="primary">保存提交</el-button>
        </el-form-item>
        <!--  考核流程部分 -->
        <el-form-item v-if="isAssessment" :class="{'el-form-item-operation':assessmentSection.tijiaoYuanCode.split(',').length>8}" label-width='100' label="提交员工">
          <el-button @click="complexPicker('tijiaoYuan')" style="width: 100%;text-align:left;overflow:hidden;" plain> {{assessmentSection.tijiaoYuanCode?assessmentSection.tijiaoYuanCode:"请选择"}}</el-button>
          <el-tooltip effect="dark" content="详情" placement="top-start">
            <el-button v-show="assessmentSection.tijiaoYuanCode.split(',').length>8" @click="showDrawer=true" class="el-form-item-operation_btn" icon="el-icon-more" circle></el-button>
          </el-tooltip>
        </el-form-item>
        <el-form-item v-if="isAssessment" label-width='100' label="上级领导审核人员">
          <el-button @click="complexPicker('superiorLeaderAuditor')" style="width: 100%;text-align:left;" plain> {{assessmentSection.superiorLeaderAuditorCode?assessmentSection.superiorLeaderAuditorCode:"请选择"}}</el-button>
        </el-form-item>
        <el-form-item v-if="isAssessment" label-width='100' label="HR审核人员">
          <el-button @click="complexPicker('HRPolpe')" style="width: 100%;text-align:left;" plain> {{assessmentSection.HRPolpeCode?assessmentSection.HRPolpeCode:"请选择"}}</el-button>
        </el-form-item>
        <el-form-item v-if="isAssessment" class="cenCen" label-width='100' label="">
          <el-button @click="assessmentSectionSub()" icon="el-icon-circle-check" style="width:400px" type="primary">保存提交</el-button>
        </el-form-item>
        <!--  考核流程部分 -->
      </el-form>

    </el-card>

    <!--抽屉 -->
    <ivDrawer drawerTitle="详情" @closeDrawer="closeDrawer" :showDrawer="showDrawer">
      <div slot="ivDrawercontent">
        <el-tag style="margin:6px;" v-if="!isAssessment&&item" v-for="(item, index) in from.code.split(',')" :key="index" effect="plain">{{item}}</el-tag>
        <el-tag style="margin:6px;" v-if="isAssessment&&item" v-for="(item, index) in assessmentSection.tijiaoYuanCode.split(',')" :key="index" effect="plain">{{item}}</el-tag>
      </div>
    </ivDrawer>

  </div>
</template>
<script>
import service from "@/api";
import $ddApi from "@/components/publicJs/utils/ddApi";
import ivDrawer from "@/components/ivDrawer";
export default {
  components: {
    ivDrawer
  },
  data() {
    return {
      //考核部分
      assessmentSection: {
        tijiaoYuanCode: "",
        tijiaoYuanId: "", //提交员工
        superiorLeaderAuditorCode: "",
        superiorLeaderAuditorId: "", //上级领导审核人员
        HRPolpeCode: "", //HR审核人员
        HRPolpeId: ""
      },
      // 评分部分
      // role_type   角色类型的值 1上级领导，2区域领导 3hr， 4审核领导
      // is_score 是否评分 0 不评分，1评分
      isAdd: true, //是否是添加流程
      query: {}, //编辑传来的数据
      loading: false, //加载
      nextLeaderItem: {
        level: "", //等级索引赋值
        auditorId: "", //ID
        code: "", //名字
        name: "", //名字
        role_type: "4", //角色类型
        is_score: "0" //是否评分 0 不评分，1评分
      }, //下一级领导添加的每一项
      nextLeader: [], //添加的数组
      showDrawer: false, //是否展示抽屉
      from: {
        // 提交表单
        area: "0", //0 无区域领导评分的流程 1有区域领导评分的流程 2 考核流程
        name: "", //流程名称
        user_ids: "", //提交员工
        code: "", //提交员工名字
        levelOne: {
          //上级评分领导
          level: "1",
          auditorId: "",
          code: "",
          name: "",
          role_type: "1",
          is_score: "1"
        },
        levelTwo: {
          // 区域评分领导
          level: "2",
          auditorId: "",
          code: "",
          name: "",
          role_type: "2",
          is_score: "1"
        },
        levelThree: {
          // HR评分人员
          level: "3",
          auditorId: "",
          code: "",
          name: "",
          role_type: "3",
          is_score: "1"
        }
      }
    };
  },
  computed: {
    // 是否是考核流程设置
    isAssessment() {
      return this.from.area == "2" ? true : false;
    }
  },
  created() {
    this.initFun();
  },
  methods: {
    async initFun() {
      this.query = this.$route.query;
      if (this.query.id) {
        // 是编辑
        this.isAdd = false;
        const { data = {} } = await service.approvalConfig_findById({
          id: this.query.id
        });
        if (data.is_examine == 1) {
          // 考核的流程
          this.from.area = "2";
          this.from.name = data.name || "";
          this.assessmentSection.tijiaoYuanCode = data.code || "";
          this.assessmentSection.tijiaoYuanId = data.user_ids || "";
          if (data.auditorList.length) {
            data.auditorList.map(item => {
              if (item.role_type == 4) {
                this.assessmentSection.superiorLeaderAuditorCode = item.name;
                this.assessmentSection.superiorLeaderAuditorId = item.auditorId;
              }
              if (item.role_type == 3) {
                this.assessmentSection.HRPolpeCode = item.name;
                this.assessmentSection.HRPolpeId = item.auditorId;
              }
            });
          }
        } else {
          // 评分的流程

          this.from.user_ids = data.user_ids;
          this.from.code = data.code;
          this.from.name = data.name;
          this.from.area = "0";
          data.auditorList.map(item => {
            //  判断区域类型
            if (item.role_type == 2) {
              this.from.area = "1";
            }
          });

          // 上级领导赋值
          this.from.levelOne.auditorId = data.auditorList[0].auditorId;
          this.from.levelOne.code = data.auditorList[0].name;
          this.from.levelOne.name = data.auditorList[0].name;

          if (this.from.area == "1") {
            // 如果是有区域领导评分的流程
            // 区域评分领导赋值
            this.from.levelTwo.auditorId = data.auditorList[1].auditorId;
            this.from.levelTwo.code = data.auditorList[1].name;
            this.from.levelTwo.name = data.auditorList[1].name;
            // HR评分人员赋值
            this.from.levelThree.auditorId = data.auditorList[2].auditorId;
            this.from.levelThree.code = data.auditorList[2].name;
            this.from.levelThree.name = data.auditorList[2].name;
          } else {
            // 区域评分领导赋值
            this.from.levelTwo.auditorId = "";
            this.from.levelTwo.code = "";
            this.from.levelTwo.name = "";
            // HR评分人员赋值
            this.from.levelThree.auditorId = data.auditorList[1].auditorId;
            this.from.levelThree.code = data.auditorList[1].name;
            this.from.levelThree.name = data.auditorList[1].name;
          }

          // 审核领导赋值
          this.nextLeader = [];
          data.auditorList.map((item, index) => {
            if (this.from.area == "1" && index > 2) {
              // 有区域领导评分的流程除开前三项
              let obj = JSON.parse(JSON.stringify(this.nextLeaderItem));
              obj.auditorId = item.auditorId;
              obj.code = item.name;
              obj.name = item.name;
              this.nextLeader.push(obj);
            }
            if (this.from.area == "0" && index > 1) {
              // 无区域领导评分的流程除开前二项
              let obj = JSON.parse(JSON.stringify(this.nextLeaderItem));
              obj.auditorId = item.auditorId;
              obj.code = item.name;
              obj.name = item.name;
              this.nextLeader.push(obj);
            }
          });
        }
      } else {
        this.addNextLeader();
      }
    },
    // 添加审核领导
    async addNextLeader() {
      if (!(await this.checkNextLeader(this.nextLeader))) {
        return;
      }
      let nextLeaderItem = JSON.parse(JSON.stringify(this.nextLeaderItem));
      nextLeaderItem.level = `${3 + this.nextLeader.length + 1}`;
      this.nextLeader.push(nextLeaderItem);
    },
    // 删除审核领导
    async deltedNextLeader(index) {
      const $confirm = await this.$confirm("此操作将进行删除");
      if (!$confirm) {
        return;
      }
      this.nextLeader.splice(index, 1);
      this.$message({
        message: "删除成功",
        type: "success"
      });
    },
    // 关闭抽屉
    closeDrawer() {
      this.showDrawer = false;
    },
    // 选人
    async complexPicker(who, index) {
      let title = "";
      let multiple = false; //是否多选
      let pickedUsers = []; //已选用户

      if (who == "user_ids") {
        // this.$notify.info({
        //   title: "温馨提示",
        //   message: "选部门无效，请务必选择部门下面的人员"
        // });
        title = "提交员工";
        multiple = true;
        if (this.from.user_ids) {
          this.from.user_ids.split(",").map(item => {
            if (item != ",") {
              pickedUsers.push(item);
            }
          });
        }
      } else if (who == "levelOne") {
        title = "上级评分领导";
        if (this.from.levelOne.auditorId) {
          pickedUsers = [this.from.levelOne.auditorId];
        }
      } else if (who == "levelTwo") {
        title = "区域评分领导";
        if (this.from.levelTwo.auditorId) {
          pickedUsers = [this.from.levelTwo.auditorId];
        }
      } else if (who == "levelThree") {
        title = "HR评分人员";
        if (this.from.levelThree.auditorId) {
          pickedUsers = [this.from.levelThree.auditorId];
        }
      }
      // 考核部分
      else if (who == "tijiaoYuan") {
        // this.$notify.info({
        //   title: "温馨提示",
        //   message: "选部门无效，请务必选择部门下面的人员"
        // });
        title = "提交员工";
        multiple = true;
        if (this.assessmentSection.tijiaoYuanId) {
          this.assessmentSection.tijiaoYuanId.split(",").map(item => {
            if (item != ",") {
              pickedUsers.push(item);
            }
          });
        }
      } else if (who == "superiorLeaderAuditor") {
        title = "上级领导审核人员";
        if (this.assessmentSection.superiorLeaderAuditorId) {
          pickedUsers = [this.assessmentSection.superiorLeaderAuditorId];
        }
      } else if (who == "HRPolpe") {
        title = "HR审核人员";
        if (this.assessmentSection.HRPolpeId) {
          pickedUsers = [this.assessmentSection.HRPolpeId];
        }
      }
      // 考核部分
      else {
        title = "审核领导";
        if (this.nextLeader[index].auditorId) {
          pickedUsers = [this.nextLeader[index].auditorId];
        }
      }
      const getUrlParamsRes = JSON.parse(
        localStorage.getItem("getUrlParamsRes")
      );
      const { users = [] } = await $ddApi.complexPicker(
        title,
        getUrlParamsRes.corpId,
        pickedUsers,
        multiple
      );
      if (users.length) {
        if (who == "user_ids") {
          this.from.user_ids = "";
          this.from.code = "";
        }
        if (who == "tijiaoYuan") {
          this.assessmentSection.tijiaoYuanCode = "";
          this.assessmentSection.tijiaoYuanId = "";
        }
        users.map(item => {
          if (who == "user_ids") {
            this.from.user_ids += `${item.emplId},`;
            this.from.code += `${item.name},`;
          } else if (who == "levelOne") {
            this.from.levelOne.auditorId = item.emplId;
            this.from.levelOne.code = item.name;
            this.from.levelOne.name = item.name;
          } else if (who == "levelTwo") {
            this.from.levelTwo.auditorId = item.emplId;
            this.from.levelTwo.code = item.name;
            this.from.levelTwo.name = item.name;
          } else if (who == "levelThree") {
            this.from.levelThree.auditorId = item.emplId;
            this.from.levelThree.code = item.name;
            this.from.levelThree.name = item.name;
          }
          // 考核部分
          else if (who == "tijiaoYuan") {
            this.assessmentSection.tijiaoYuanId += `${item.emplId},`;
            this.assessmentSection.tijiaoYuanCode += `${item.name},`;
          } else if (who == "superiorLeaderAuditor") {
            this.assessmentSection.superiorLeaderAuditorId = item.emplId;
            this.assessmentSection.superiorLeaderAuditorCode = item.name;
          } else if (who == "HRPolpe") {
            this.assessmentSection.HRPolpeId = item.emplId;
            this.assessmentSection.HRPolpeCode = item.name;
          }
          // 考核部分
          else {
            this.nextLeader[index].auditorId = item.emplId;
            this.nextLeader[index].code = item.name;
            this.nextLeader[index].name = item.name;
          }
        });
      }
    },
    // 检验领导是否可以继续添加
    checkNextLeader(arr = []) {
      let value = true;
      for (let i = 0; i < arr.length; i++) {
        if (!arr[i].auditorId) {
          value = false;
          this.$message({
            message: `请选择第${i + 1}级审核领导`,
            type: "warning"
          });
          break;
        }
      }
      return new Promise(resolve => {
        resolve(value);
      });
    },
    // 考核流程提交
    async assessmentSectionSub() {
      if (!this.from.name) {
        this.$message({
          message: `请填写流程名称`,
          type: "warning"
        });
        return;
      }
      if (!this.assessmentSection.superiorLeaderAuditorId) {
        this.$message({
          message: `请填写上级领导审核人员`,
          type: "warning"
        });
        return;
      }
      if (!this.assessmentSection.HRPolpeId) {
        this.$message({
          message: `请填写HR审核人员`,
          type: "warning"
        });
        return;
      }
      const $confirm = await this.$confirm("此操作将数据提交");
      if (!$confirm) {
        return;
      }
      let subData = {
        name: this.from.name, //流程名称
        user_ids: this.assessmentSection.tijiaoYuanId, //提交员工
        user_name: this.assessmentSection.tijiaoYuanCode,
        code: this.assessmentSection.tijiaoYuanCode,
        is_examine: 1, //0 评分审核流程 1考评审核流程
        auditorList: ""
      };
      let auditorList = [];
      // 添加上级领导审核人员
      auditorList.push({
        level: "1",
        auditorId: this.assessmentSection.superiorLeaderAuditorId,
        auditorName: this.assessmentSection.superiorLeaderAuditorCode,
        name: this.assessmentSection.superiorLeaderAuditorCode,
        role_type: "4" //1上级领导，2区域领导 3hr， 4审核领导
      });
      // HR审核人员
      auditorList.push({
        level: "2",
        auditorId: this.assessmentSection.HRPolpeId,
        auditorName: this.assessmentSection.HRPolpeCode,
        name: this.assessmentSection.HRPolpeCode,
        role_type: "3" //1上级领导，2区域领导 3hr， 4审核领导
      });
      subData.auditorList = JSON.stringify(auditorList);
      this.loading = true;
      let res = {};
      if (!this.isAdd) {
        // 编辑
        subData.id = this.query.id;
        res = await service.approvalConfig_edit(subData);
      } else {
        res = await service.approvalConfig_saveApprovel(subData);
      }
      this.loading = false;
      if (res.success) {
        this.$message({
          message: "保存成功",
          type: "success"
        });
        this.$router.go(-1);
      }
    },
    // 评分流程提交表单
    async subFrom() {
      if (!this.from.name) {
        this.$message({
          message: `请填写流程名称`,
          type: "warning"
        });
        return;
      }
      if (!this.from.levelOne.auditorId) {
        this.$message({
          message: `请选择上级评分领导`,
          type: "warning"
        });
        return;
      }
      if (this.from.area == "1" && !this.from.levelTwo.auditorId) {
        this.$message({
          message: `请选择区域评分领导`,
          type: "warning"
        });
        return;
      }
      if (!this.from.levelThree.auditorId) {
        this.$message({
          message: `请选择HR评分人员`,
          type: "warning"
        });
        return;
      }
      const $confirm = await this.$confirm("此操作将数据提交");
      if (!$confirm) {
        return;
      }

      let subData = {
        name: this.from.name, //流程名称
        user_ids: this.from.user_ids, //提交员工
        code: this.from.code,
        is_examine: 0, //0 评分审核流程 1考评审核流程
        auditorList: ""
      };
      let auditorList = [];
      auditorList.push(this.from.levelOne); //添加上级评分领导

      if (this.from.area == "1") {
        // 有区域领导评分的流程
        auditorList.push(this.from.levelTwo); //添加区域领导
      }

      auditorList.push(this.from.levelThree); //添加hr
      this.nextLeader.map(item => {
        //添加审核领导
        if (item.auditorId) {
          auditorList.push(item);
        }
      });

      // 修改level规范类型根据索引来
      auditorList.map((item, index) => {
        item.level = `${index + 1}`;
      });

      subData.auditorList = JSON.stringify(auditorList);

      this.loading = true;
      let res = {};
      if (!this.isAdd) {
        // 编辑
        subData.id = this.query.id;
        res = await service.approvalConfig_edit(subData);
      } else {
        res = await service.approvalConfig_saveApprovel(subData);
      }
      this.loading = false;
      if (res.success) {
        this.$message({
          message: "保存成功",
          type: "success"
        });
        this.$router.go(-1);
      }
    }
  }
};
</script>
<style scoped>
.from_box {
  width: 70%;
  min-width: 800px;
  height: auto;
  margin: auto;
}
.el-form-item-operation {
  position: relative;
  padding-right: 68px;
}
.el-form-item-operation_btn {
  position: absolute;
  right: -56px;
  top: 50%;
}
</style>
